<?php
namespace app\api\exception;

use think\exception\Handle;
use think\exception\HttpException;
use think\exception\ValidateException;
use think\Response;
use Throwable;
use think\facade\Db;
/**
 * 异常处理类
 */
class Http extends Handle
{
    public function render($request, Throwable $e): Response
    {

        $url = ''; //跳转地址
        //判断当前异常类有没有getHeaders方法
        if(in_array('getHeaders',get_class_methods($e))){
            //$headers = $e->getHeaders();
            $headers = call_user_func([$e,'getHeaders']);
            if(isset($headers['redirect_url'])) $url = $headers['redirect_url'];
            if(isset($headers['data'])) $data = $headers['data'];
        }

        //返回数据
        $result = [
            'status'         => 0,
            'msg'           => $e->getMessage(),
            'err_file' => $e->getFile().'::'.$e->getLine(),
            'redirect_url'   => $url, //app不需要,其他需要
        ];
        if(!empty($data)) {
            $result['data'] = $data;
        }
        //自定义错误码 例：abort(500, 'err string', ['status'=>100])
        if(!empty($headers['status'])) {
            $result['status'] = $headers['status'];
        }
        dump($e);exit;
        //dump(123);exit;

        //apilog 失败|错误
        $c_arr = explode('\\', get_class($e));
        $result['err'] = array_pop($c_arr);

        $this->apiLog(0,$result);
        unset($result['err']);
        //直接请求api，出现异常时只返回json

        return json($result);
    }
    public function apilog($status,$result){
        //数据
        $args = input(false); //不过滤，防新guid被过滤
        //移除公共的路由参数
        unset($args['service'],$args['method'],$args['s']);
        $arg = $args;


        //请求数据
        $data_log = [
            "api" => input('service').'/'.input('method'),
            'arg' => json_encode($arg, JSON_UNESCAPED_UNICODE + JSON_UNESCAPED_SLASHES + JSON_NUMERIC_CHECK),
            "ip" => request()->ip(),
            "w_time" => time(),
            'headers' => json_encode(request()->header(), JSON_UNESCAPED_UNICODE + JSON_UNESCAPED_SLASHES + JSON_NUMERIC_CHECK),
        ];
        //当前用户Id

        if(!empty($args['token'])) {
            $user = json_decode(base64_decode($args['token']),true);
            $data_log['user_id'] = $user['user_id']??'';
        }
        //返回结果
        $data_log['status'] = $status;

        $data_log['result'] = json_encode($result, JSON_UNESCAPED_UNICODE + JSON_UNESCAPED_SLASHES + JSON_NUMERIC_CHECK);
        if(strlen($data_log['result']) > 60000) {
            $data_log['result'] = '数据太多，不记录';
        }

        //保存
        $request_id = Db::name('api_log')->insertGetId($data_log);
    }
}
